//
//  DYJUserViewController.m
//  Piece
//
//  Created by dllo on 16/6/14.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "DYJUserViewController.h"
#import "HFStretchableTableHeaderView.h"
#import "DYJUserTableViewCell.h"
#import "DYJUserContentTableViewCell.h"
#import "DYJCollectionViewController.h"

#import "XZHHomeCollectionViewController.h"
#import "XZHHomeCollectionViewCell.h"

#import "MBProgressHUD.h"
#import "SDImageCache.h"
#import "XZHMovieCollectionViewController.h"
#import "XZHHomeNoteCollectionViewController.h"
#import "DYJDataBaseTool.h"
#import "XZHHomeNoteModel.h"
#import "OtherViewController.h"
#import "UIImageView+WebCache.h"

@interface DYJUserViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *userTableView;
@property (nonatomic, strong) HFStretchableTableHeaderView *stretchHeaderView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *imageViewArray;
@property (nonatomic, retain) MBProgressHUD *hud;
@end

@implementation DYJUserViewController {
    NSMutableArray *noteDataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDataFromDataBase];
    [self createUserTableView];
    [self createArray];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.76 green:0.79 blue:0.83 alpha:1.00];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
#pragma mark -- 创建tableView
- (void)createUserTableView
{
    _userTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    _userTableView.separatorStyle = 0;
    _userTableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.99 blue:1.00 alpha:1.00];
    _userTableView.delegate = self;
    _userTableView.dataSource = self;
    [self.view addSubview:_userTableView];
    
    [self createHeadView];
    
    //注册cell
    [_userTableView registerNib:[UINib nibWithNibName:@"DYJUserTableViewCell" bundle:nil] forCellReuseIdentifier:@"userCell"];
    [_userTableView registerNib:[UINib nibWithNibName:@"DYJUserContentTableViewCell"  bundle:nil] forCellReuseIdentifier:@"userContentCell"];
}
#pragma mark -- 创建数组
- (void)createArray
{
    _titleArray = @[@"收藏", @"图文",@"文章", @"电影", @"消息", @"设置", @"其他设置", @"清除缓存"];
    _imageViewArray = @[@"center_setting", @"user_picture", @"user_reading", @"user_movie", @"user_message", @"center_setting", @"center_setting", @"center_setting"];
}
#pragma mark -- 创建头视图
- (void)createHeadView
{
    //背景图
    UIImageView *coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 320 * FitHeight)];
    coverImageView.image = [UIImage imageNamed:@"personalBackgroundImage"];
    coverImageView.contentMode = UIViewContentModeScaleAspectFill;
    coverImageView.layer.masksToBounds = YES;
    coverImageView.clipsToBounds = YES;
    
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 320)];
    [headerView addSubview:coverImageView];
    //小记
    UIImageView *noteBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(33 * FitWidth, 172 * FitHeight, 120 * FitWidth, 120 * FitHeight)];
    noteBgImageView.image = [UIImage imageNamed:@"music_cover_small"];
    [headerView addSubview:noteBgImageView];
    
    UIImageView *noteImageView = [[UIImageView alloc] initWithFrame:CGRectMake(33 * FitWidth, 172 * FitHeight, 120 * FitWidth, 120 * FitHeight)];
    if (noteDataSource.count != 0) {
        XZHHomeNoteModel *model = [noteDataSource objectAtIndex:0];
        
        if ([model.image isEqualToString:@"(null)"]) {
            [noteImageView sd_setImageWithURL:[NSURL URLWithString:model.placeholderImage]];
        } else {
            NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:model.image];
            UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
            noteImageView.image = _decodedImage;
        }
    } else {
        noteImageView.image = [UIImage imageNamed:@"music_cover_small"];
    }
    noteImageView.layer.borderWidth = 2;
    noteImageView.layer.borderColor = [UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1.00].CGColor;
    noteImageView.contentMode = UIViewContentModeScaleAspectFill;
    noteImageView.layer.masksToBounds = YES;
    [headerView addSubview:noteImageView];
    noteImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapNoteImage)];
    [noteImageView addGestureRecognizer:tap];
    
    
    //歌单
    UIImageView *songBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(210 * FitWidth, 171 * FitHeight, 126 * FitWidth, 125 * FitHeight)];
    songBgImageView.image = [UIImage imageNamed:@"center_cd"];
    [headerView addSubview:songBgImageView];
    
//    songBgImageView.layer.masksToBounds = YES;
//    songBgImageView.layer.borderWidth = 2;
//    songBgImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    UIImageView *songImageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 2, 110 * FitWidth, 118 * FitHeight)];
    songImageView.image = [UIImage imageNamed:@"music_cover_small"];
    [songBgImageView addSubview:songImageView];
    //返回按钮
    UIImageView *returnImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 20, 20)];
    returnImageView.image = [UIImage imageNamed:@"return"];
    returnImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapReturn = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapReturn)];
    [returnImageView addGestureRecognizer:tapReturn];
    [headerView addSubview:returnImageView];
    
    self.stretchHeaderView = [HFStretchableTableHeaderView new];
    [self.stretchHeaderView stretchHeaderForTableView:self.userTableView withView:coverImageView subViews:headerView];
    
}

- (void)getDataFromDataBase
{
    DYJDataBaseTool *dataBaseTool = [DYJDataBaseTool shareDYJDataBaseTool];
    NSMutableArray *array = [dataBaseTool selectAllNote];
    noteDataSource = [NSMutableArray arrayWithArray:array];
}

- (void)didTapNoteImage {
    XZHHomeNoteCollectionViewController *ncvc = [[XZHHomeNoteCollectionViewController alloc] init];
    [self.navigationController pushViewController:ncvc animated:NO];
}

#pragma mark -- 实现返回
- (void)didTapReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- 清理缓存
- (void)startClean{
    //    NSArray * paths =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //    self.filePath = [paths lastObject];
    //    unsigned long long size = [self fileSizeAtPath:[paths lastObject]];
    CGFloat size = [[SDImageCache sharedImageCache] checkTmpSize];
    NSString *contents = [NSString stringWithFormat:@"%@ %.2fM，%@",@"当前缓存大小为",size,@"是否清除？"];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"清除缓存" message:contents delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    
    for(UIView *subview in alert.subviews)
    {
        if([[subview class] isSubclassOfClass:[UILabel class]])
        {
            UILabel *label = (UILabel*)subview;
            
            label.textAlignment = NSTextAlignmentLeft;
        }
    }
    
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
        self.hud = HUD;
        [self.view addSubview:HUD];
        HUD.center = self.view.center;
        HUD.minSize = CGSizeMake(110.0f, 70.0f);
        HUD.mode = MBProgressHUDModeIndeterminate;
        HUD.labelText = @"正在帮您清理";
        [HUD showWhileExecuting:@selector(clear) onTarget:self withObject:nil animated:YES];
    }
}
//清除缓存
- (void)clear
{
    //    NSLog(@"%lu",size);
    
    //    NSFileManager *manager = [NSFileManager defaultManager];
    //        NSArray*array=[manager contentsOfDirectoryAtPath:self.filePath error:nil];
    //
    //    for (NSString*str in array)
    //    {
    //        NSString*newPath=[NSString stringWithFormat:@"%@/%@",self.filePath,str];
    //        [manager removeItemAtPath:newPath error:nil];
    //    }
    
    //    [[SDImageCache sharedImageCache] clearMemory];
    //    [[SDImageCache sharedImageCache] cleanDisk];
    sleep(1);
    [[SDImageCache sharedImageCache] clearDisk];
    self.hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"black_tips_ok.png"]];
    self.hud.mode = MBProgressHUDModeCustomView;
    self.hud.labelText = @"清除成功";
    sleep(1);
}
//代理方法
- (void)clean
{
    [self startClean];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 || indexPath.row == 5)
    {
        return 30;
    }
    else
    {
        return 42;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 || indexPath.row == 5) {
        DYJUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userCell"];
        cell.titleLabel.text = [_titleArray objectAtIndex:indexPath.row];
        cell.selectionStyle = 0;
        return cell;
    }
    else
    {
        DYJUserContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userContentCell"];
        cell.titleLabel.text = [_titleArray objectAtIndex:indexPath.row];
        cell.headerImageView.image = [UIImage imageNamed:[_imageViewArray objectAtIndex:indexPath.row]];
        cell.selectionStyle = 0;
        if (indexPath.row == 4 || indexPath.row == 7) {
            cell.lineView.hidden = YES;
        }
        if (indexPath.row == 7) {
            cell.footerLineView.hidden = NO;
        }
        else
        {
            cell.footerLineView.hidden = YES;
        }
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            XZHHomeCollectionViewController *cvc  = [[XZHHomeCollectionViewController alloc] init];
            [self.navigationController pushViewController:cvc animated:YES];
        }
            break;
        case 2:
        {
            DYJCollectionViewController *cvc = [[DYJCollectionViewController alloc] init];
            [self.navigationController pushViewController:cvc animated:YES];
        }
            break;
        case 3:
        {
            XZHMovieCollectionViewController *mvc = [[XZHMovieCollectionViewController alloc] init];
            [self.navigationController pushViewController:mvc animated:YES];
        }
            break;
        case 4:
        {
            
        }
            break;
        case 5:
        {
            
        }
            break;
        case 6:
        {
            OtherViewController *ovc = [[OtherViewController alloc] init];
            [self.navigationController pushViewController:ovc animated:YES];
        }
            break;
        case 7:
        {
            [self startClean];
        }
            break;
        default:
            break;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.stretchHeaderView scrollViewDidScroll:scrollView];
}

- (void)viewDidLayoutSubviews
{
    [self.stretchHeaderView resizeView];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
